// pages/map/map.js
import * as echarts from '../../ec-canvas/echarts.js';

import provinceNameMap from '../functions/provinceNameMap.js'
import provinceIDMap from '../functions/provinceIDMap.js'
var checkconfig = require("../functions/checkconfig.js");

var that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ecMap: {
      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
    },
    provinName: "省份名",
    array: ["全部", "蛔虫", "钩虫", "蓝氏贾第鞭毛虫", "鞭虫", "蛲虫", "华支睾吸虫", "毛圆线虫", "缩小壳膜绦虫", "带绦虫", "微小壳膜绦虫", "布氏姜片虫"],
    index: 0, //默认显示位置
    items: [],
    switch: false
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
    this.provinceMap(that.data.provinName);

  },
  async downloadProvinceData(provinceID) {
    // 云文件地址
    wx.cloud.init();
    const fileID = 'cloud://cloud1-1gf0pek44e15f87b.636c-cloud1-1gf0pek44e15f87b-1324701592/provinces/11.js'
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    const tempFilePath = await wx.cloud
      .downloadFile({
        fileID,
      })
      .then((res) => {
        return res.tempFilePath;
      })
      .catch((err) => {
        return "";
      });

    wx.hideLoading();
    return tempFilePath;
  },

  /**
   * 省份分布地图
   */
  async provinceMap(province) {
    var that = this;
    console.log("跳转:", province)
    wx.cloud.init();
    var provinceID = provinceIDMap[province]
    var tempFilePath = await this.downloadProvinceData(provinceID)
    console.log("临时文件链接：", tempFilePath)
    wx.getFileSystemManager().readFile({
      filePath: tempFilePath, // 获取的临时或本地文件路径
      encoding: 'utf-8',
      success(resd) {
        var provinceSelected = JSON.parse(resd.data); 
        console.log("读取文件信息：", provinceSelected.features)
        var provinceName = provinceNameMap[province]

        that.ecComponent.init((canvas, width, height) => {
          let myMap = echarts.init(canvas, null, {
            width: width,
            height: height
          });
          canvas.setChart(myMap);
          echarts.registerMap(provinceName, provinceSelected); // 绘制中国地图
    
          const option = {
            // title: {
            //   text: province +'寄生虫感染概率'
    
            // },
            geo: [{
              // 地理坐标系组件
              map: provinceName,
              roam: true, //支持拖拽缩放
              scaleLimit: {
                //滚轮缩放的极限控制
                min: 1, //缩放最小大小
                max: 6, //缩放最大大小
              },
              aspectScale: 1, // 比例
              layoutCenter: ["50%", "37%"], // position位置
              layoutSize: 370, // 地图大小，保证了不超过 370x370 的区域
              label: {
                // 图形上的文本标签
                normal: {
                  show: true,
                  textStyle: {
                    color: "rgba(0, 0, 0, 0.9)",
                    fontSize: '8'
                  },
                  overflow: "break"
                },
                emphasis: { // 高亮时样式
                  color: "#333"
                }
              },
              itemStyle: {
                // 图形上的地图区域
                normal: {
                  borderColor: "rgba(0,0,0,0.2)",
                  areaColor: "#005dff"
                }
              }
            }],
            visualMap: {
              min: 0,
              max: 1,
              show: false,
              // text: ['High', 'Low'],
              realtime: false,
              hoverLink: true,
              calculable: true,
              inRange: {
                color: ['lightskyblue', 'yellow', 'orangered']
              }
            },
            series: [{
              type: 'map',
              mapType: provinceName,
              geoIndex: 0,
              roam: true, //支持拖拽缩放
              scaleLimit: {
                //滚轮缩放的极限控制
                min: 0.5, //缩放最小大小
                max: 6, //缩放最大大小
              },
              label: {
                normal: {
                  show: false
                },
                emphasis: {
                  show: false
                }
              },
              data: that.getRandomData(provinceSelected)
            }]
          };
          myMap.setOption(option);
          return myMap
        })
      },
    })



  },

  getRandomData(geoJson) {
    var data = []
    for (let i = 0; i < geoJson.features.length; i++) {
      var itemMap = {}
      itemMap.name = geoJson.features[i].properties.name
      itemMap.value = randomData()
      data.push(itemMap)
    };
    return data;
  },

  getTable(province) {
    var names = ["蛔虫", "钩虫", "蓝氏贾第鞭毛虫", "鞭虫", "蛲虫", "华支睾吸虫", "毛圆线虫", "缩小壳膜绦虫", "带绦虫", "微小壳膜绦虫", "布氏姜片虫"];
    var items = []
    for (let i = 0; i < names.length; i++) {
      var item = {}
      item["name"] = names[i]
      item["value"] = randomData()
      item["code"] = i
      items.push(item)
    }
    console.log(items)
    this.setData({
      items: items,
    })
  },

  url(e) {
    var item_index = e.currentTarget.dataset.index;
    // console.log(questionIndex)
    wx.navigateTo({
      url: '../eggs/eggs?pageIndex=1&index=' + item_index,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let flag = await checkconfig.checkconfig()
    console.log(flag)
    this.setData({
      switch: flag
    })
    this.ecComponent = this.selectComponent('#mychart-dom-map');
    console.log(options)
    this.provinceMap(options.name);
    this.getTable(options.name);
    this.setData({
      provinName: options.name,
      index: options.index
    })
    that = this;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

/**
 * 生成1000以内的随机数
 */
function randomData() {
  return Math.random();
}